package jehc.djshi.sys.web;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BasePage;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.base.BaseSearch;
import jehc.djshi.common.entity.OauthAccountEntity;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.sys.model.XtKnowledge;
import jehc.djshi.sys.service.XtKnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;

/**
 * @Desc 平台知识内容
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/xtKnowledge")
@Api(value = "平台知识内容API",tags = "平台知识内容API",description = "平台知识内容API")
public class XtKnowledgeController extends BaseAction {
	@Autowired
	private XtKnowledgeService xtKnowledgeService;
	/**
	* 加载初始化列表数据并分页
	* @param baseSearch
	 * @throws UnsupportedEncodingException 
	 * @throws UnsupportedEncodingException 
	*/
	@NeedLoginUnAuth
	@PostMapping(value="/list")
	@ApiOperation(value="查询平台知识内容列表并分页", notes="查询平台知识内容列表并分页")
	public BasePage getXtKnowledgeListByCondition(@RequestBody(required=true)BaseSearch baseSearch) throws UnsupportedEncodingException{
		Map<String, Object> condition = new HashMap<String, Object>();
//		String keywords = ""+baseSearch.convert().get("keywords");
//		if(!StringUtils.isEmpty(keywords)){
//			BasePage bpage = baseSearch.ConvertToBasePage();
//			int start = 0;
//			int limit = 30;
//			Integer offset = bpage.getStart();
//			Integer pageSize = bpage.getLimit();
//			if(null != offset){
//				start = new Integer(offset);
//			}
//			if(null != pageSize){
//				limit = new Integer(pageSize);
//			}
//			//////////////////采用SOLR关键词查询//////////////
//			PageSolr pageSolr = new PageSolr();
//			condition.put("keywords",keywords.trim());
//	        pageSolr.setConditions(condition);
//	        pageSolr.setCurrent(start);//当前页从0开始
//	        pageSolr.setSize(limit);
//	        SolrCore solrCore = getSolrCoreByUseonlynumbercode("xtknowledge");
//	        pageSolr = solrQueryPage(solrCore.getSolr_url_url()+"/"+solrCore.getSolr_core_name(), pageSolr);
//	        List<Object> list = pageSolr.getDatas();
//	        return outPageStr(list, pageSolr.getCount(), baseSearch);
//		}
        //////////////////采用SQL关键词查询///////////////
		condition =  baseSearch.convert();
		commonHPager(baseSearch);
		List<XtKnowledge> xtKnowledgeList = xtKnowledgeService.getXtKnowledgeListByCondition(condition);
		for(XtKnowledge xtKnowledge:xtKnowledgeList){
			if(!StringUtil.isEmpty(xtKnowledge.getCreate_id())){
				OauthAccountEntity createBy = getAccount(xtKnowledge.getCreate_id());
				if(null != createBy){
					xtKnowledge.setCreateBy(createBy.getName());
				}
			}
			if(!StringUtil.isEmpty(xtKnowledge.getUpdate_id())){
				OauthAccountEntity modifiedBy = getAccount(xtKnowledge.getUpdate_id());
				if(null != modifiedBy){
					xtKnowledge.setModifiedBy(modifiedBy.getName());
				}
			}
		}
		PageInfo<XtKnowledge> page = new PageInfo<XtKnowledge>(xtKnowledgeList);
		return outPageStr(page,baseSearch);
	}

	/**
	 * 查询
	 * @param keywords
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/query")
	@ApiOperation(value="查询平台知识内容列表", notes="查询平台知识内容列表")
	public List<XtKnowledge> query(BaseSearch baseSearch,String keywords){
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("xt_knowledge_title",keywords);
		commonHPager(baseSearch);
		List<XtKnowledge> xt_KnowledgeList = xtKnowledgeService.getXtKnowledgeListByCondition(condition);
		return xt_KnowledgeList;
	}

	/**
	* 查询单个平台知识内容
	* @param xt_knowledge_id
	*/
	@NeedLoginUnAuth
	@GetMapping(value="/get/{xt_knowledge_id}")
	@ApiOperation(value="查询单个平台知识内容", notes="查询单个平台知识内容")
	public BaseResult getXtKnowledgeById(@PathVariable("xt_knowledge_id")String xt_knowledge_id){
		XtKnowledge xtKnowledge = xtKnowledgeService.getXtKnowledgeById(xt_knowledge_id);
		if(!StringUtil.isEmpty(xtKnowledge.getCreate_id())){
			OauthAccountEntity createBy = getAccount(xtKnowledge.getCreate_id());
			if(null != createBy){
				xtKnowledge.setCreateBy(createBy.getName());
			}
		}
		if(!StringUtil.isEmpty(xtKnowledge.getUpdate_id())){
			OauthAccountEntity modifiedBy = getAccount(xtKnowledge.getUpdate_id());
			if(null != modifiedBy){
				xtKnowledge.setModifiedBy(modifiedBy.getName());
			}
		}
		return outDataStr(xtKnowledge);
	}
	/**
	* 添加
	* @param xtKnowledge
	*/
	@PostMapping(value="/add")
	@ApiOperation(value="创建单个平台知识内容", notes="创建单个平台知识内容")
	public BaseResult addXtKnowledge(@RequestBody XtKnowledge xtKnowledge){
		int i = 0;
		if(null != xtKnowledge){
			xtKnowledge.setXt_knowledge_id(toUUID());
			i=xtKnowledgeService.addXtKnowledge(xtKnowledge);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	/**
	* 修改
	* @param xtKnowledge
	*/
	@PutMapping(value="/update")
	@ApiOperation(value="编辑单个平台知识内容", notes="编辑单个平台知识内容")
	public BaseResult updateXtKnowledge(@RequestBody XtKnowledge xtKnowledge){
		int i = 0;
		if(null != xtKnowledge){
			i=xtKnowledgeService.updateXtKnowledge(xtKnowledge);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	/**
	* 删除
	* @param xt_knowledge_id
	*/
	@DeleteMapping(value="/delete")
	@ApiOperation(value="删除平台知识内容", notes="删除平台知识内容")
	public BaseResult delXtKnowledge(String xt_knowledge_id){
		int i = 0;
		if(!StringUtil.isEmpty(xt_knowledge_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("xt_knowledge_id",xt_knowledge_id.split(","));
			i=xtKnowledgeService.delXtKnowledge(condition);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

//	/**
//     * 分页查询，包含查询，分页，高亮及获取高亮处摘要等内容；不同于数据库的查询分页，
//     * solr的查询返回值中有文档总数，所以无需再次查询总条数。
//     * @param baseURL 自定义的翻页对象，包含查询信息及当前页数据列表。
//     */
//    public static PageSolr solrQueryPage(String baseURL,PageSolr pageSolr) {
//        SolrQuery query = new SolrQuery();
//        //为防止和其他变量重名，在变量的开始加上condition的首字母
//        if(null != pageSolr.getConditions().get("keywords") && !"".equals(pageSolr.getConditions().get("keywords"))){
//        	 String keywords = pageSolr.getConditions().get("keywords").toString();
//             query.setQuery("xt_knowledge_keywords:"+SolrUtil.escapeQueryChars(keywords)); //OR必须大写或用“空格”、“||”代替
//             //query.setQuery("xt_knowledge_title:"+keywords+" OR xt_knowledge_content:"+keywords+""); //OR必须大写或用“空格”、“||”代替
//        }
//        /////////////操作排序功能
//        query.addSort("xt_time", SolrQuery.ORDER.desc);
//        query.setStart((int)pageSolr.getStart());
//        query.setRows((int)pageSolr.getSize());
//        //设置高亮
//        query.setHighlight(true);//开启高亮组件
//        query.addHighlightField("xt_knowledge_title");//高亮字段
//        query.addHighlightField("xt_knowledge_content");//高亮字段
//        query.addHighlightField("xt_knowledge_keywords");//高亮字段
//        query.setHighlightSimplePre("<font color='red'>");//标记，高亮关键字前缀
//        query.setHighlightSimplePost("</font>");//后缀
//        query.setHighlight(true).setHighlightSnippets(1);//获取高亮分片数，一般搜索词可能分布在文章中的不同位置，其所在一定长度的语句即为一个片段，默认为1，但根据业务需要有时候需要多取出几个分片。 - 此处设置决定下文中titleList, contentList中元素的个数
//        query.setHighlightFragsize(150);//每个分片的最大长度，默认为100。适当设置此值，如果太小，高亮的标题可能会显不全；设置太大，摘要可能会太长。
//        List<Object> xtKonwledgeList = new ArrayList<Object>();
//        try {
//        	//连接solr服务器
//    		HttpSolrServer server = new HttpSolrServer(baseURL);
//            QueryResponse rsp = server.query(query);
//            SolrDocumentList docs = rsp.getResults();
//            //获取所有高亮的字段
//            Map<String,Map<String,List<String>>> highlightMap=rsp.getHighlighting();
//            Iterator<SolrDocument> iter = docs.iterator();
//            while (iter.hasNext()) {
//                SolrDocument doc = iter.next();
//                String idStr = doc.getFieldValue("id").toString();
//                XtKnowledge xtKnowledge = new XtKnowledge();
//                xtKnowledge.setXt_knowledge_id(doc.getFieldValue("xt_knowledge_id").toString());
//                xtKnowledge.setXt_knowledge_content(doc.getFieldValue("xt_knowledge_content").toString());
//                xtKnowledge.setXt_knowledge_title(doc.getFieldValue("xt_knowledge_title").toString());
//                xtKnowledge.setXt_userinfo_realName(doc.getFieldValue("xt_userinfo_realName").toString());
//                xtKnowledge.setXt_time(DateUtils.formatDateTime((Date)doc.getFieldValue("xt_time")));
//                List<String> xt_knowledge_titleList =highlightMap.get(idStr).get("xt_knowledge_title");
//                List<String> xt_knowledge_contentList=highlightMap.get(idStr).get("xt_knowledge_contentList");
//                //获取并设置高亮的字段标题
//                if(null != xt_knowledge_titleList && !xt_knowledge_titleList.isEmpty()){
//                	xtKnowledge.setXt_knowledge_title(xt_knowledge_titleList.get(0));
//                }
//                //获取并设置高亮的字段内容
//                if(xt_knowledge_contentList!=null && xt_knowledge_contentList.size()>0){
//                	xtKnowledge.setXt_knowledge_content(xt_knowledge_contentList.get(0));
//                }
//                xtKonwledgeList.add(xtKnowledge);
//            }
//            pageSolr.setDatas(xtKonwledgeList);
//            pageSolr.setCount(docs.getNumFound());
//            return pageSolr;
//        } catch (Exception e) {
//        	e.printStackTrace();
//        	throw new ExceptionUtil(e.getMessage(),e.getCause());
//        }
//    }
    
//    /**
//     * 自动补全
//     * @param keywords     * @return
//     */
//    @NeedLoginUnAuth
//	@GetMapping(value="/autolist")
//    public BaseResult autoXtKnowledgeListByCondition(String keywords){
//    	if(StringUtil.isEmpty(keywords)){
//    		return null;
//    	}
//    	SolrCore solrCore = getSolrCoreByUseonlynumbercode("xtknowledge");
//    	return outItemsStr(SolrUtil.autoCompleteByFacet(solrCore,"xt_knowledge_keywords", SolrUtil.escapeQueryChars(keywords.trim()), null,10));
//    }

	/**
	 * 知识库数
	 * @return
	 */
	@GetMapping(value="/count")
	@NeedLoginUnAuth
	@ApiOperation(value="知识库数", notes="知识库数")
	public BaseResult count(){
		int count = xtKnowledgeService.getXtKnowledgeCount(new HashMap<>());
		return outDataStr(count);
	}
}
